package com.zhangsun.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangsun.expection.BusinessException;
import com.zhangsun.system.entity.DictEntity;
import com.zhangsun.system.mapper.DictMapper;
import com.zhangsun.system.service.DictService;
import com.zhangsun.system.vo.dict.DictEditVo;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author zhangsun
 * @since 2019-08-13
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, DictEntity> implements DictService {

    @Override
    public List<DictEntity> findAllByCode(String code) {
        LambdaQueryWrapper<DictEntity> queryWrapper = new QueryWrapper<DictEntity>().lambda();
        queryWrapper.eq(DictEntity::getTypeCode, code)
                .orderByAsc(DictEntity::getSort);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public void create(DictEditVo vo) {
        checkValue(vo.getTypeCode(), vo.getValue(), null);

        DictEntity dictEntity = new DictEntity();
        BeanUtil.copyProperties(vo, dictEntity);
        dictEntity.insert();
    }

    @Override
    public DictEntity findById(String id) {
        return baseMapper.selectById(id);
    }

    @Override
    public void update(String id, DictEditVo vo) {
        checkValue(vo.getTypeCode(), vo.getValue(), id);

        DictEntity dictEntity = new DictEntity();
        BeanUtil.copyProperties(vo, dictEntity);
        dictEntity.setId(id);
        dictEntity.updateById();
    }

    private void checkValue(String typeCode, String value, String id) {
        LambdaQueryWrapper<DictEntity> queryWrapper = new QueryWrapper<DictEntity>().lambda();
        queryWrapper.eq(DictEntity::getTypeCode, typeCode)
                .eq(DictEntity::getValue, value);
        if (StrUtil.isNotBlank(id)) {
            queryWrapper.ne(DictEntity::getId, id);
        }
        int count = baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException("此分类下该值已存在");
        }
    }

    @Override
    public void delete(String id) {
        baseMapper.deleteById(id);
    }
}
